﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;
using FJASPX.Framwork.Helper;
using FJASPX.Framwork.Config;

namespace FJASPX.UI.Extention
{
    /// <summary>
    /// 无图片输入默认图
    /// </summary>
    public class ImageModule : IHttpModule
    {
        #region IHttpModule Members
        public void Dispose()
        {
            //throw new NotImplementedException();
        }
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpResponse response = HttpContext.Current.Response;
            HttpRequest request = HttpContext.Current.Request;
            string imagePath = request.PhysicalPath;
            if (imagePath != null && (
                imagePath.ToLower().EndsWith(".jpg") ||
                imagePath.ToLower().EndsWith(".jpeg") ||
                imagePath.ToLower().EndsWith(".png")))
            {
                if (!File.Exists(imagePath))
                {
                    using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(
                    ConfigBase.GetConfig("DefaultImagePath", true))))
                    {
                        img.Save(response.OutputStream, ImageFormat.Jpeg);
                        response.End();
                        return;
                    }
                }
                //下面防止盗链
                //else if (request.RawUrl.ToLower().Contains(
                //    Configuration.ConfigBase.GetConfig("Domain", true).
                //    Replace("http://", "").Replace("https://", "")))
                //{
                //    using (Image img = Image.FromFile(HttpContext.Current.Server.MapPath(
                //           Configuration.ConfigBase.GetConfig("DefaultImagePath", true))))
                //    {
                //        img.Save(response.OutputStream, ImageFormat.Jpeg);
                //        response.End();
                //        return;
                //    }
                //}

            }
        }

        #endregion
    }
}
